package edu.fpa.day0719;

public class SetArrayList3<E>{
    private Object[] elementDate;
    private int size;
    public SetArrayList3() {
        elementDate = new Object[10];
    }
    public SetArrayList3(int i) {
        if(i<0) {
            throw new RuntimeException("容量不能为负数");
        }else if(i==0){
            elementDate = new Object[10];
        }
        else {
            elementDate = new Object[i];
        }
        elementDate = new Object[i];
    }
    public void add(E e) {
        if(size==elementDate.length) {
            Object[] NewArray = new Object[elementDate.length+(elementDate.length>>1)];
            System.arraycopy(elementDate, 0, NewArray, 0, elementDate.length);
            elementDate = NewArray;
        }
        elementDate[size++] = e;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i=0;i<size;i++) {
            sb.append(elementDate[i]+",");
        }
        sb.setCharAt(sb.length()-1, ']');
        return sb.toString();
    }
    public void set(E e,int index) {
        checkRange(index);
        elementDate[index] = e;

    }
    public E get(int index) {
        checkRange(index);
        return (E)elementDate[index];
    }
    public void checkRange(int index) {
        if(index<0||index>size-1) {
            throw new RuntimeException("索引不合法："+index);
        }
    }
    public static void main(String[] args) {
        SetArrayList3<String> s = new SetArrayList3<>(20);
        for(int i=0;i<40;i++)
        {s.add(i+":ab");}
        System.out.println(s);
        System.out.println(s.get(10));
        s.set("aaaaaa", 10);
        System.out.println(s.get(10));
        System.out.println(s.get(-10));

    }
}